import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { NovelChapter } from './entities/novel-chapter.entity';
import { Novel } from './entities/novel.entity';
import {
  PaginationUtil,
  PaginationOptions,
} from '../../common/utils/pagination.util';

@Injectable()
export class NovelChapterService {
  constructor(
    @InjectRepository(NovelChapter)
    private chapterRepository: Repository<NovelChapter>,
    @InjectRepository(Novel)
    private novelRepository: Repository<Novel>,
  ) {}

  /**
   * 创建章节
   */
  async create(createChapterDto: any): Promise<NovelChapter> {
    const {
      novelId,
      title,
      content,
      chapterNumber: inputChapterNumber,
    } = createChapterDto;

    // 验证小说是否存在
    const novel = await this.novelRepository.findOne({
      where: { id: novelId },
    });
    if (!novel) {
      throw new NotFoundException('小说不存在');
    }

    let chapterNumber = inputChapterNumber;

    // 检查章节号是否已存在
    if (chapterNumber) {
      const existingChapter = await this.chapterRepository.findOne({
        where: { novelId, chapterNumber },
      });
      if (existingChapter) {
        throw new BadRequestException('章节号已存在');
      }
    } else {
      // 自动生成章节号
      const lastChapter = await this.chapterRepository.findOne({
        where: { novelId },
        order: { chapterNumber: 'DESC' },
      });
      chapterNumber = lastChapter ? lastChapter.chapterNumber + 1 : 1;
    }

    const chapter = new NovelChapter();
    chapter.novelId = novelId;
    chapter.title = title;
    chapter.content = content;
    chapter.chapterNumber = chapterNumber;
    chapter.wordCount = content ? content.length : 0;

    // 更新小说总字数
    novel.wordCount = (novel.wordCount || 0) + chapter.wordCount;
    await this.novelRepository.save(novel);

    return this.chapterRepository.save(chapter);
  }

  /**
   * 获取小说的章节列表
   */
  async findByNovelId(novelId: number, options: PaginationOptions = {}) {
    const { limit, offset } = PaginationUtil.parse(options);

    const [chapters, total] = await this.chapterRepository.findAndCount({
      where: { novelId },
      order: { chapterNumber: 'ASC' },
      take: limit,
      skip: offset,
    });

    return PaginationUtil.createResponse(chapters, total, options);
  }

  /**
   * 获取单个章节
   */
  async findOne(id: number): Promise<NovelChapter> {
    const chapter = await this.chapterRepository.findOne({
      where: { id },
      relations: ['novel'],
    });

    if (!chapter) {
      throw new NotFoundException('章节不存在');
    }

    return chapter;
  }

  /**
   * 根据小说ID和章节号获取章节
   */
  async findByNovelAndChapter(
    novelId: number,
    chapterNumber: number,
  ): Promise<NovelChapter> {
    const chapter = await this.chapterRepository.findOne({
      where: { novelId, chapterNumber },
      relations: ['novel'],
    });

    if (!chapter) {
      throw new NotFoundException('章节不存在');
    }

    return chapter;
  }

  /**
   * 更新章节
   */
  async update(id: number, updateChapterDto: any): Promise<NovelChapter> {
    const chapter = await this.findOne(id);
    const { title, content } = updateChapterDto;

    // 计算字数变化
    const oldWordCount = chapter.wordCount || 0;
    const newWordCount = content ? content.length : 0;
    const wordCountDiff = newWordCount - oldWordCount;

    if (title !== undefined) {
      chapter.title = title;
    }
    if (content !== undefined) {
      chapter.content = content;
      chapter.wordCount = newWordCount;
    }

    const savedChapter = await this.chapterRepository.save(chapter);

    // 更新小说总字数
    if (wordCountDiff !== 0) {
      await this.novelRepository.increment(
        { id: chapter.novelId },
        'wordCount',
        wordCountDiff,
      );
    }

    return savedChapter;
  }

  /**
   * 删除章节
   */
  async remove(id: number): Promise<void> {
    const chapter = await this.findOne(id);

    // 更新小说总字数
    await this.novelRepository.decrement(
      { id: chapter.novelId },
      'wordCount',
      chapter.wordCount || 0,
    );

    await this.chapterRepository.remove(chapter);
  }

  /**
   * 获取上一章节
   */
  async findPreviousChapter(
    novelId: number,
    chapterNumber: number,
  ): Promise<NovelChapter | null> {
    return this.chapterRepository.findOne({
      where: { novelId, chapterNumber: chapterNumber - 1 },
    });
  }

  /**
   * 获取下一章节
   */
  async findNextChapter(
    novelId: number,
    chapterNumber: number,
  ): Promise<NovelChapter | null> {
    return this.chapterRepository.findOne({
      where: { novelId, chapterNumber: chapterNumber + 1 },
    });
  }

  /**
   * 获取小说的第一章
   */
  async findFirstChapter(novelId: number): Promise<NovelChapter | null> {
    return this.chapterRepository.findOne({
      where: { novelId },
      order: { chapterNumber: 'ASC' },
    });
  }

  /**
   * 获取小说的最后一章
   */
  async findLastChapter(novelId: number): Promise<NovelChapter | null> {
    return this.chapterRepository.findOne({
      where: { novelId },
      order: { chapterNumber: 'DESC' },
    });
  }

  /**
   * 获取章节总数
   */
  async getChapterCount(novelId: number): Promise<number> {
    return this.chapterRepository.count({
      where: { novelId },
    });
  }

  /**
   * 批量创建章节
   */
  async createBatch(createChaptersDto: any[]): Promise<NovelChapter[]> {
    const results: NovelChapter[] = [];
    let totalWordCount = 0;

    for (const createChapterDto of createChaptersDto) {
      const chapter = await this.create(createChapterDto);
      results.push(chapter);
      totalWordCount += chapter.wordCount;
    }

    return results;
  }

  /**
   * 重新排序章节
   */
  async reorderChapters(
    novelId: number,
    chapterOrders: { id: number; chapterNumber: number }[],
  ): Promise<void> {
    // 验证所有章节都属于该小说
    const chapterIds = chapterOrders.map((order) => order.id);
    const chapters = await this.chapterRepository.find({
      where: { id: In(chapterIds) },
    });

    for (const chapter of chapters) {
      if (chapter.novelId !== novelId) {
        throw new BadRequestException(
          `章节 ${chapter.id} 不属于小说 ${novelId}`,
        );
      }
    }

    // 更新章节号
    for (const order of chapterOrders) {
      await this.chapterRepository.update(order.id, {
        chapterNumber: order.chapterNumber,
      });
    }
  }
}
